<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q">
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArtList">筛选</el-button>
            <el-button type="info" size="small" @click="resetList">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" size="small" class="btn-pub" @click="pubVisible=true">发表文章</el-button>
      </div>

      <!-- 文章表格区域 -->
      <el-table :data="artList" style="width: 100%;" border stripe>
        <el-table-column label="文章标题" prop="title">
          <template v-slot="{row}">
            <el-link type="primary" @click="showDetail(row.id)">{{row.title}}</el-link>
          </template>
        </el-table-column>
        <el-table-column label="分类" prop="cate_name"></el-table-column>
        <el-table-column label="发表时间" prop="pub_date">
          <template v-slot="{row}">
            {{ dateFormat(row.pub_date) }}
          </template>
        </el-table-column>
        <el-table-column label="状态" prop="state"></el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button type="danger" size="mini" @click="remove(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="q.pagenum"
      :page-sizes="[2, 3, 5, 20]"
      :page-size="q.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>

    <!-- 发表文章弹框 -->
    <el-dialog title="发表文章" :visible.sync="pubVisible" fullscreen :before-close="handleClose">
      <!-- 发布文章的对话框 -->
      <el-form :model="pubForm" :rules="pubFormRules" ref="pubForm" label-width="100px">
        <el-form-item label="文章标题" prop="title">
          <el-input v-model="pubForm.title" placeholder="请输入标题"></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="cate_id">
          <el-select v-model="pubForm.cate_id" placeholder="请选择分类" style="width: 100%;">
            <el-option :label="item.cate_name" :value="item.id" v-for="item in cateList" :key="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <quill-editor v-model="pubForm.content" @blur="$refs.pubForm.validateField('content')"></quill-editor>
        </el-form-item>

        <el-form-item label="文章封面" prop="cover_img">
          <!-- 用来显示封面的图片 -->
          <img v-if="preview" :src="preview" alt="" class="cover-img" ref="imgRef" />
          <img v-else src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
          <br />
          <!-- 文件选择框，默认被隐藏 -->
          <input type="file" style="display: none;" accept="image/*" ref="iptFileRef" @change="changeImg"/>
          <!-- 选择封面的按钮 -->
          <el-button type="text" @click="$refs.iptFileRef.click()">+ 选择封面</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
          <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看文章详情的对话框 -->
    <el-dialog title="文章预览" :visible.sync="detailVisible" width="80%">
      <h1 class="title">{{ artDetail.title }}</h1>

      <div class="info">
        <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
        <span>发布时间：{{ dateFormat(artDetail.pub_date) }}</span>
        <span>所属分类：{{ artDetail.cate_name }}</span>
        <span>状态：{{ artDetail.state }}</span>
      </div>

      <!-- 分割线 -->
      <el-divider></el-divider>

      <!-- 文章的封面 -->
      <img :src="'http://www.liulongbin.top:3008' + artDetail.cover_img" alt="" />

      <!-- 文章的详情 -->
      <div v-html="artDetail.content" class="detail-box"></div>
    </el-dialog>
  </div>
</template>

<script>
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  data () {
    return {
      // 查询参数对象
      cateList: [],
      preview: '',
      // 文章列表
      artList: [],
      total: 0,
      q: {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      },
      pubForm: {
        title: '',
        cate_id: '',
        content: '',
        cover_img: '',
        state: ''
      },
      pubFormRules: {
        title: [
          { required: true, message: '请输入文章标题', trigger: 'blur' },
          { min: 1, max: 30, message: '文章标题的长度为1-30个字符', trigger: 'change' }
        ],
        cate_id: [{ required: true, message: '请选择文章标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
        cover_img: [{ required: true, message: '请选择封面照片', trigger: 'blur' }]
      },
      pubVisible: false,
      // 文章详情
      detailVisible: false,
      artDetail: []
    }
  },
  methods: {
    // 分页区换页和每页条数的触发函数
    handleSizeChange (val) {
      // console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.getArtList()
    },
    handleCurrentChange (val) {
      // console.log(`当前页: ${val}`)
      this.q.pagenum = val
      this.getArtList()
    },
    /* // 关闭事件的处理函数
    async handleClose (done) {
      // 询问用户是否确认关闭对话框
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      // 取消了关闭
      if (confirmResult === 'cancel') return
      // 确认关闭
      done()
    } */
    async handleClose (done) {
      const confirmResult = await this.$confirm('此操作将导致文章信息丢失，是否继续？', '提示框', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      // console.log(confirmResult)
      if (confirmResult === 'cancel') return
      done()
    },
    // 获取文章列表
    async getCateList () {
      const { data: res } = await this.$axios.get('/my/cate/list')
      // console.log(res)
      this.cateList = res.data
    },
    changeImg (e) {
      // 将图片转换成可读模式
      const file = e.target.files[0]
      // console.dir(file)
      // console.log(file)
      if (file) {
        this.pubForm.cover_img = file
        // 将文件file对象转换成img的src可读取的BASE64或者URL
        this.preview = URL.createObjectURL(file)
        // 手动校验封面是否上传
      } else {
        this.preview = ''
        this.cover_img = ''
      }
      // 手动校验需要发在最底下
      this.$refs.pubForm.validateField('cover_img')
    },
    pubArticle (state) {
      this.pubForm.state = state
      this.$refs.pubForm.validate(async valid => {
        // console.log(valid)
        if (!valid) return
        const fd = new FormData()
        Object.keys(this.pubForm).forEach(k => fd.append(k, this.pubForm[k]))
        const { data: res } = await this.$axios.post('/my/article/add', fd)
        // console.log(res)
        if (res.code !== 0) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.pubVisible = false
        this.$refs.iptFileRef.value = ''
        this.$refs.pubForm.resetFields()
        this.preview = ''
        this.getArtList()
      })
    },
    // 发送文章列表请求
    async getArtList () {
      const { data: res } = await this.$axios.get('/my/article/list', { params: this.q })
      // console.log(res)
      if (res.code === 0) {
        this.artList = res.data
        this.total = res.total
      }
    },
    dateFormat (date) {
      return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
    },
    resetList () {
      this.q = {
        pagenum: 1,
        pagesize: 2,
        cate_id: '',
        state: ''
      }
      this.getArtList()
    },
    async showDetail (id) {
      const { data: res } = await this.$axios.get('/my/article/info', { params: { id } })
      // console.log(res)
      if (res.code === 0) {
        this.artDetail = res.data
      }
      this.detailVisible = true
    },
    remove (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete('/my/article/info', { params: { id } })
        // console.log(res)
        if (res.code === 0) {
          if (this.artList.length === 1 && this.q.pagenum > 1) {
            this.q.pagenum--
          }
          this.getArtList()
        }
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  },
  created () {
    this.getCateList()
    this.getArtList()
  }
}
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// scoped 作用: 可以让当前样式只对当前 template 中的元素生效
// scoped 原理:
// 1. 给当前组件内 template 中所有的标签加上 data-v-hash 属性
// 2. 给当前组件内 style 中所有的选择器加上属性交集选择器 .ql-editor[data-v-hash]
// 注意事项: 只会给当前 template 中的标签加上 data-v-hash, 如果是组件, 则只会给组件的根标签加 data-v-hash

// .quill-editor { // 不能设置给父盒子高度, 子盒子使用的高度是 100% 会导致错位
// 直接设置无法生效, 为什么?
// 因为 scoped 只会给组件的根标签加上 data-v-hash, 而应用样式时使用的是属性交集选择器: .ql-editor[data-v-hash]
// 子标签中并没有 data-v-hash 属性, 只有组件的根节点才有这个属性

// 解决方案:
// 1. 删除 scoped
// 问题: 样式容易产生冲突
// 2. 深度选择器 -> LESS -> /deep/
// 原理: 将属性交集选择器变成属性后代选择器
/deep/ .ql-editor {
  height: 300px;
}

// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}

.el-pagination {
  margin-top: 15px;
}

.title {
  font-size: 24px;
  text-align: center;
  font-weight: normal;
  color: #000;
  margin: 0 0 10px 0;
}

.info {
  font-size: 12px;
  span {
    margin-right: 20px;
  }
}

// 修改 dialog 内部元素的样式，需要添加样式穿透
/deep/ .detail-box {
  img {
    width: 500px;
  }
}
</style>
